from os.path import exists
from typing import Union
from ...addon.install_pillow import install_pillow, pillow_is_installed


def blur_image(org_img_path:str, save_img_path:str, blur_level:int) -> Union[None, int]:

    ##################################################################
    # import/check if pillow are installed:
    ##################################################################
    PIL_INSTALLED = pillow_is_installed()
    if not PIL_INSTALLED:
        # Si no estuviera instalado lo intentamos instalar por ultima vez:
        instalation_successfully = install_pillow()
        if not instalation_successfully:
            print("⏺ Failed to install Pillow. Please install it manually.")
            return -1
    ##################################################################

    # Verificar si la ruta del archivo existe:
    if not exists(org_img_path):
        print(f"The {org_img_path} file path does not exist.")
        return -1
    
    from PIL import Image, ImageFilter
    OriImage = Image.open(org_img_path)
    # OriImage.show()

    # Applying BoxBlur filter
    # blured_image = OriImage.filter(ImageFilter.BoxBlur(blur_level))

    # Applying GaussianBlur filter
    blured_image = OriImage.filter(ImageFilter.GaussianBlur(blur_level))
    
    # Convert the image to RGB mode (if it's not already in RGB mode)
    blured_image = blured_image.convert("RGB")
    blured_image.show()

    # Save Blured Image:
    blured_image.save(save_img_path)